<template>
  <div class="app-container">
    <div class="settle-manage">
      <el-form :inline="true" :model="dataFilter" class="search-form">
        <el-form-item label="所属商户" class="form-item-wrapper">
          <el-select v-model="dataFilter.tenantId" placeholder="请选择所属商户" clearable style="width: 180px;"
            @change="loadLocationData" filterable remote :remote-method="searchMerchant">
            <el-option v-for="item in merchantList" :key="item.id" :label="item.tenantName" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="所在地点位置" class="form-item-wrapper">
          <el-tree-select v-model="dataFilter.locationIds" :data="fullLocationTree" multiple collapse-tags collapse-tags-tooltip 
            :render-after-expand="false" show-checkbox :filter-node-method="filterNodeMethod" filterable node-key="id"
            value-key="id" :props="locationTreeProps" placeholder="请选择所在地点位置" clearable style="width: 180px" />
        </el-form-item>

        <el-form-item label="结算周期" class="form-item-wrapper">
          <el-select v-model="dataFilter.billingCycle" placeholder="请选择结算周期" clearable style="width: 130px">
            <el-option v-for="item in billingCycleOption" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="企业名称" class="form-item-wrapper">
          <el-input v-model="dataFilter.name" placeholder="请输入企业名称" style="width: 200px" />
        </el-form-item>

        <el-form-item label="企业简称" class="form-item-wrapper">
          <el-input v-model="dataFilter.shortName" placeholder="请输入企业简称" style="width: 150px" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>

      <div style="margin-bottom: 20px;">
        <el-button type="primary" @click="handleAdd">添加</el-button>
        <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
        <span style="margin-left: 10px; color: #909399; font-size: 14px;">
          已选择 {{ selectedRows.length }} 条
        </span>
      </div>
      <el-table :data="sourceData.list" border highlight-current-row stripe row-key="id" style="width: 100%"
        @selection-change="handleSelectionChange" v-loading="loading">
        <el-table-column type="selection" header-align="center" width="40" />
        <el-table-column label="企业名称" prop="name" min-width="160" />
        <el-table-column label="企业简称" prop="shortName" />
        <el-table-column label="联系人" prop="contactPerson" width="75" />
        <el-table-column label="联系电话" prop="customerPhone" />
        <el-table-column label="所在地点位置" prop="location" min-width="100" />
        <el-table-column label="所属商户" prop="tenantName" />
        <el-table-column label="计费配置" prop="isConfig" width="85">
          <template #default="{ row }">
            <span>{{ row.isConfig == 1 ? '已配置' : '未配置' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结算周期" prop="billingCycleName" />
        <el-table-column label="当前账期" prop="billPeriod" width="115" />
        <el-table-column label="开始日期" prop="startDate" />
        <el-table-column label="结束日期" prop="endDate" />
        <el-table-column label="结算状态" prop="settleStatus" width="85"/>
        <el-table-column label="操作" align="center" min-width="120">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">
              详情
            </el-button>
            <el-button type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination :pageProps="pageProps" layout="prev, pager, next" @current-change="getList" />
    </div>
  </div>

  <EnterpriseManagementDialog ref="dialog" @listChange="itemData" />
</template>

<script lang="ts" setup>
import { reactive, ref, nextTick, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { 
  getEnterprise, 
  deleteEnterpriseById,
  batchDeleteEnterprise,
  getEnterpriseDetail,
  getMerchantByName,
  getLocationTree
} from "@/api/settle";
import Pagination from "@/components/Pagination/Index.vue";
import EnterpriseManagementDialog from "./components/EnterpriseManagementDialog.vue";
import { LocationTreeNode } from '@/api/types/location'

const loading = ref(false)
const selectedRows = ref<any[]>([]);

const dataFilter = reactive({
  name: undefined as string | undefined,
  shortName: undefined as string | undefined,
  tenantId: undefined as number | undefined,
  billingCycle: undefined as number | undefined,
  locationIds: [],
});

const billingCycleOption = ref<any>([
  { name: '按月结算', value: 0 },
  { name: '按季度结算', value: 1 },
  { name: '按半年结算', value: 2 },
  { name: '按年结算', value: 3 },
])

// 商户列表
const merchantList = ref<any[]>([]);

// 获取商户列表
const getMerchantList = (name?: string) => {  
  // 使用新的按名称查询接口
  getMerchantByName(name).then((res: any) => {
    if (res.success && res.data) {
      merchantList.value = Array.isArray(res.data) ? res.data : []
    } else {
      console.warn('未获得到商户列表:', res)
      merchantList.value = []
    }
  }).catch((err: any) => {
    console.error('获取商户列表失败', err)    
  })
};

const searchMerchant = (name: string) => {
  getMerchantList(name)
}

// 复选框选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

// 页面加载时获取商户列表
onMounted(() => {
  getMerchantList();
  getList();
});

const pageProps = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});

const sourceData = reactive({
  list: [] as any[],
});

const getList = () => {
  loading.value = true;
  getEnterprise({
    pageNum: pageProps.value.pageNum,
    pageSize: pageProps.value.pageSize,
    ...dataFilter
  }).then((res: any) => {
    loading.value = false;
    console.log("res", res);
    sourceData.list = res.data.records || [];
    pageProps.value.total = res.data.total || 0;
  })
  .catch((err: any) => {
    loading.value = false;
    console.error("err", err);
    sourceData.list = [];
    pageProps.value.total = 0;
  });
};

const handleSearch = () => {
  pageProps.value.pageNum = 1; // 搜索时重置到第一页
  getList();
};

const onReset = () => {
  dataFilter.name = undefined;
  dataFilter.shortName = undefined;
  dataFilter.tenantId = undefined;
  dataFilter.billingCycle = undefined;
  dataFilter.locationIds = [];
  Object.assign(pageProps.value, {
    pageNum: 1,
    pageSize: 10,
    total: 0,
  });
  getList(); // 重置后重新获取数据
};

const dialog = ref<any>(null);

const handleAdd = () => {
  dialog.value.dialogVisible = true;
  dialog.value.dialogStatus = "create";
  dialog.value.isDisabled = true;
};

const handleView = (row: any) => {
  dialog.value.dialogVisible = true;
  dialog.value.dialogStatus = "view";
  dialog.value.isDisabled = false;
  nextTick(() => {
    getEnterpriseDetail(row.id)
    .then((res: any) => {
      // 先重置表单
      dialog.value.reset();
      // 然后设置数据
      Object.assign(dialog.value.tableItem, res.data);
    })
    .catch((err: any) => {
      console.error("获取企业详情失败:", err);
    });
  });
};

const handleEdit = (row: any) => {
  dialog.value.dialogVisible = true;
  dialog.value.dialogStatus = "edit";
  dialog.value.isDisabled = true;
  nextTick(() => {
    getEnterpriseDetail(row.id)
    .then((res: any) => {
      // 先重置表单
      dialog.value.reset();
      // 然后设置数据
      Object.assign(dialog.value.tableItem, res.data);
    })
    .catch((err: any) => {
      console.error("获取企业详情失败（编辑）:", err);
    });
  });
};

const itemData = () => {
  getList();
};

const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    "确定要删除吗?",
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
  .then(() => {  
    // 单个删除，使用路径参数
    deleteEnterpriseById(row.id)
    .then((res: any) => {
      ElMessage.success("删除成功！");
      getList();
    })
    .catch((err: any) => {
      console.error("err", err.msg);
      ElMessage.error("删除失败！");
    });
  })
  .catch((err: any) => {
    console.error("删除企业失败:", err);
  });
};

const handleBatchDelete = () => {
  ElMessageBox.confirm(
    '确定要批量删除吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {  
    const params = {
      idList: selectedRows.value.map(item=>item.id)
    }
    batchDeleteEnterprise(params)
    .then((res: any) => {
      ElMessage.success('删除成功！')
      getList()
    })
    .catch((err: any) => {
      console.error('err', err.msg)
      ElMessage.success('删除失败！')
      getList()
    })
  })
  .catch(() => {})
}

// 地点位置数据
const fullLocationTree = ref<LocationTreeNode[]>([])
const locationTreeProps = ref({
  label: 'name'
});

// 加载地点位置数据
const loadLocationData = async () => {
  try {
    if (!dataFilter.tenantId) {
      fullLocationTree.value = []
      return
    }
    
    const res = await getLocationTree(dataFilter.tenantId)
    if (res.success && res.data) {
      fullLocationTree.value = res.data
    } else {
      const errorMsg = res.msg || '加载地点位置数据失败'
      ElMessage.error(`加载失败: ${errorMsg}`)
      fullLocationTree.value = []
    }
  } catch (error) {
    ElMessage.error('网络请求失败，请检查网络连接后重试')
    fullLocationTree.value = []
  }
}

const filterNodeMethod = (value: string, data: any) => {
  return value ? data.name.includes(value) : true;
}
</script>

<style lang="scss" scoped>
.app-container {
  flex: 1;
}
.form-item-wrapper {
  margin-right: 10px;
}
</style>